import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:share_fit/app/helper/storage_mixin.dart';
import 'package:share_fit/app/network/net_const.dart';
import 'package:share_fit/app/network/net_tool.dart';
import 'package:share_fit/app/tools/locale_tool.dart';
import 'package:share_fit/app/tools/log_utils.dart';

class UTEPedBind with StorageMixin {
  /// 设备在线绑定

  static const baseUrl = 'https://watchapp.wiodo.tech';
  static const registrationUrl = "$baseUrl/api/v2/registration";

  // static const bindUrl = "$baseUrl/r";
  static const devicesUrl = "$baseUrl/api/v2/devices";


  void init() {
    initStorage();
  }

  void startBind(String deviceId, String sn, Function callback) {
    logger.d("startBind...");
    registration().then((value) => {
          if (value.isNotEmpty)
            {bindDevice(value, deviceId, sn).then((value) => callback(value))}
          else
            {callback(false)}
        });
  }

  Future<String> registration() async {
    logger.d("registration...");
    try {
      final dio = Dio();
      dio.options.headers.addAll(NetTool.getHeadersWithToken());
      dio.options.contentType = ContentType.json.toString();
      dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
      Response response = await dio.post(registrationUrl);
      Map map = jsonDecode(response.toString());
      logger.d(response.toString());
      if (map[NetConst.keyCode] == NetConst.statusSuccess) {
        return map[NetConst.keyData][NetConst.keyUrl];
      }
    } on DioException catch (e) {
      if (e.response?.statusCode == NetConst.statusForbidden) {
        logger.d("on 403 error");
      }
    } catch (e) {
      logger.d(e);
    }

    return "";
  }

  Future<bool> bindDevice(String url, String deviceId, String sn) async {
    logger.d("bindDevice...");
    try {
      final dio = Dio();
      dio.options.headers.addAll(NetTool.getHeadersWithToken());
      dio.options.contentType = ContentType.json.toString();
      dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
      Response response =
      await dio.post(url, data: {NetConst.keyParentId: deviceId, NetConst.keySN: sn});
      Map map = jsonDecode(response.toString());
      logger.d(response.toString());
      return map[NetConst.keyCode] == NetConst.statusSuccess;
    } on DioException catch (e) {
      if (e.response?.statusCode == NetConst.statusForbidden) {
        logger.d("on 403 error");
      }
    } catch (e) {
      logger.d(e);
    }

    return false;
  }

  Future<List<dynamic>> queryDevices(String deviceId) async {
    logger.d("queryDevices...");
    try {
      final dio = Dio();
      dio.options.headers.addAll(NetTool.getHeadersWithToken());
      dio.options.contentType = ContentType.json.toString();
      dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
      Response response =
      await dio.get(devicesUrl, data: {NetConst.keyParentId: deviceId});
      logger.d(response.toString());
      Map map = jsonDecode(response.toString());
      if (map[NetConst.keyCode] == NetConst.statusSuccess) {
        return map[NetConst.keyData]["devices"];
      }
    } on DioException catch (e) {
      if (e.response?.statusCode == NetConst.statusForbidden) {
        logger.d("on 403 error");
      }
    } catch (e) {
      logger.d(e);
    }

    return [];
  }

  Future<bool> deleteDevice(String deviceId, String sn) async {
    logger.d("deleteDevice...");
    if (!NetTool.hasToken()) {
      logger.d("delete device failed, user not login");
      return false;
    }

    try {
      final dio = Dio();
      dio.options.headers.addAll(NetTool.getHeadersWithToken());
      dio.options.contentType = ContentType.json.toString();
      dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
      Response response = await dio.delete("$devicesUrl/$deviceId?${NetConst.keySN}=$sn&${NetConst.keyDomainId}=default");
      logger.d(response.toString());
      Map map = jsonDecode(response.toString());
      if (map[NetConst.keyCode] == NetConst.statusSuccess) {
        return true;
      }
    } on DioException catch (e) {
      if (e.response?.statusCode == NetConst.statusForbidden) {
        logger.d("on 403 error");
      }
    } catch (e) {
      logger.d(e);
    }

    return false;
  }
}
